#include "base/channel.h"
#include "base/eventloop.h"
#include "base/log.h"
#include <sys/socket.h>
#include <fcntl.h>

#include "net/accept.h"
namespace net_tools::net{

Accept::Accept(func new_accept,net_tools::Eventloop* eventloop)
  :socket_(),
   listen_fd_(socket_.Get_socket()),
   eventloop_(eventloop)
{
  Socket::Set_noblocked(socket_.Get_socket());
  channel_ = eventloop_->Get_free_channel(listen_fd_);
  channel_->Set_read_callback(std::move(new_accept));
};
Accept::~Accept(){
  eventloop_->Free_channel(channel_);
};
void Accept::Init_listen(int port){
  Socket::Set_reused(listen_fd_);
  struct sockaddr_in listen_addr;
  listen_addr.sin_family = AF_INET;
  listen_addr.sin_port = htons(port);
  listen_addr.sin_addr.s_addr = INADDR_ANY;
  NT_LOG_INFO << bind(listen_fd_,reinterpret_cast<sockaddr*>(&listen_addr),sizeof(sockaddr_in)) << NT_LOG_ENDL;
  channel_->Enableread();
  channel_->Add_to_epoll();
  listen(listen_fd_,_C::MAX_WAIT_ACCEPT);
  NT_LOG_INFO << fcntl(listen_fd_,F_GETFL,0) << NT_LOG_ENDL;
};
// need in right thread
void Accept::Stop_listen(){
  channel_->Disableall();
  channel_->Del_to_epoll();
};

} // namespace net_tools::net